//
//  SensorScanner.m
//  Sensornet
//
//  Created by Chris Karr on 9/22/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "SensorScanner.h"
#import <Carbon/Carbon.h>

#define SENSOR_NAME @"Name"
#define ENABLED @"Enabled"
#define COLOR @"Color"
#define VALUE @"Value"

@implementation SensorScanner

- (void) awakeFromNib
{
	NSTimer * timer = [[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(update:) userInfo:nil repeats:YES] retain];
	[timer fire];
}

- (void) update:(NSTimer *) theTimer
{
	NSString * nameScript = @"if application \"Pennyworth\" is running then\n\
								tell application \"Pennyworth\"\n\
									name of observations\n\
								end tell\n\
							end if";
	
	NSAppleScript * scpt = [[NSAppleScript alloc] initWithSource:nameScript];
	
	if (scpt != nil)
	{
		NSDictionary * errors = nil;
		
		NSAppleEventDescriptor * results = [scpt executeAndReturnError:&errors];

		[scpt release];
		
		NSMutableArray * sensorList = [NSMutableArray array];
		
		int i = 1;
		for (i = 1; i <= [results numberOfItems]; i++)
		{
			NSAppleEventDescriptor * item = [results descriptorAtIndex:i];

			[sensorList addObject:[item stringValue]];
		}

		for (NSMutableDictionary * sensor in [sensors arrangedObjects])
			[sensor setObject:[NSArchiver archivedDataWithRootObject:[NSColor redColor]] forKey:COLOR];
		
		for (NSString * sensorName in sensorList)
		{
			NSString * obsSource = [NSString stringWithFormat:@"tell application \"Pennyworth\"\n\
																value of observation named \"%@\"\n\
															 end tell", sensorName];

			NSAppleScript * obsValueScript = [[NSAppleScript alloc] initWithSource:obsSource];
			
			NSAppleEventDescriptor * obsResults = [obsValueScript executeAndReturnError:&errors];
			
			NSString * value = [obsResults stringValue];
			
			BOOL found = NO;
			
			for (NSMutableDictionary * sensor in [sensors arrangedObjects])
			{
				if ([[sensor valueForKey:SENSOR_NAME] isEqual:sensorName])
				{
					found = YES;
					[sensor setObject:[NSArchiver archivedDataWithRootObject:[NSColor blackColor]] forKey:COLOR];
					[sensor setValue:value forKey:VALUE];
				}
			}
			
			if (!found)
			{
				NSMutableDictionary * sensor = [NSMutableDictionary dictionary];
				
				[sensor setValue:sensorName forKey:SENSOR_NAME];
				[sensor setValue:[NSNumber numberWithBool:NO] forKey:ENABLED];
				[sensor setObject:[NSArchiver archivedDataWithRootObject:[NSColor blackColor]] forKey:COLOR];
				[sensor setValue:value forKey:VALUE];
				
				[sensors addObject:sensor];
			}
		}
	}
}

@end
